﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PeachLite.Entity;
using PeachLite.Helpers;
using System.Data;
using System.Text;
using System.IO;

namespace PeachLite.Admin.X
{
    /// <summary>
    /// FiManger 的摘要说明
    /// </summary>
    public class FiManger : AjaxBase
    {
        protected const string TIME_FORMAT1 = "yyyyMMdd";
        protected const string TIME_FORMAT2 = "yyyyMMddHHmmss";

        #region 方法

        protected override SysMessage Do(int code)
        {
            SysMessage m;
            if (code != -1)
            {
                switch (code)
                {
                    case 111301:
                        m = DeleteFile(Context);
                        break;
                    case 111302:
                        m = GetFileList(Context);
                        break;
                    case 111303:
                        m = FiUploader(Context);
                        break;
                    default:
                        m = new SysMessage();
                        m.Success = false;
                        m.Message = "业务代码有误";
                        break;
                }
            }
            else
            {
                m = new SysMessage();
                m.Success = false;
                m.Message = "业务代码有误";
            }
            return m;
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage DeleteFile(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string p = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();
            if (p == "")
            {
                m.Success = false;
                m.Message = "路径为空！";
                return m;
            }

            m = FileHelper.DeleteFile(context.Server.MapPath(p));
            return m;
        }

        /// <summary>
        /// 获得文件列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage GetFileList(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string LIST_FORMAT = "<li  p='{4}' type='{6}' onclick='{5}'><dl><dt><a title='{3}'><img src='{0}' alt='{2}' /></a><span class='del' onclick='FileManger.deleteFile(this);'>×</span></dt><dd>{1}</dd></dl></li>";
            string DEFAULT_DIRECTOR = "/u";

            string path = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();
            string root = context.Request.Form["root"] == null ? "" : context.Request.Form["root"].Trim();
            path = path.Replace("\\", "/");
            root = root.Replace("\\", "/");
            root = string.IsNullOrWhiteSpace(root) ? DEFAULT_DIRECTOR : root;

            if (path == "" | !path.StartsWith(root))
            {
                path = root;
            }
            try
            {
                DataTable tab = FileHelper.GetFile(context.Server.MapPath(path));
                StringBuilder sb = new StringBuilder(string.Empty);
                for (int i = 0; i < tab.Rows.Count; i++)
                {
                    string name = tab.Rows[i]["Name"].ToString();
                    string icon = "";
                    string onclick = "FileManger.selectSingleFile(this);";
                    string p = path.EndsWith("/") ? path + name : path + "/" + name;
                    string type = "file";
                    switch (tab.Rows[i]["Type"].ToString())
                    {
                        case "folder":
                            icon = "resx/img/folder-64.gif";
                            onclick = "FileManger.getFileList(\"" + p + "\");";
                            type = "folder";
                            break;
                        case "image":
                            icon = p;
                            break;
                        case "doc":
                            icon = "resx/img/doc_80.png";
                            break;
                        case "excel":
                            icon = "resx/img/excel_80.png";
                            break;
                        default:
                            icon = "resx/img/text_80.png";
                            break;
                    }
                    sb.Append(string.Format(LIST_FORMAT, icon, name, name, name, p, onclick, type));
                }
                string backPath = path.LastIndexOf('/') < 0 ? path : path.Substring(0, path.LastIndexOf('/'));
                m.Code = 0;
                m.Success = true;
                m.O = new { BackPath = backPath, FileList = sb.ToString() };
                return m;
            }
            catch (Exception ex)
            {
                m.Success = false;
                m.Message = ex.Message;
                return m;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private SysMessage FiUploader(HttpContext context)
        {
            SysMessage m = new SysMessage();
            string root = context.Request.Form["p"] == null ? "" : context.Request.Form["p"].Trim();
            string id = context.Request.Form["id"] == null ? "" : context.Request.Form["id"].Trim();
            if (root == "")
            {
                m.Success = false;
                m.Message = "保存路径为空!";
                return m;
            }
            else
            {
                root = root.Replace("\\", "/");
            }
            if (id == "")
            {
                m.Success = false;
                m.Message = "file控件名为空!";
                return m;
            }
            //获得file控件
            HttpPostedFile file = context.Request.Files[id];

            //检查控件是否为空
            if (file == null)
            {
                m.Success = false;
                m.Message = "名为" + id + "的file控件为空！";
                return m;
            }
            string fileName = file.FileName;

            //检查文件是否为空
            if (string.IsNullOrWhiteSpace(fileName))
            {
                m.Success = false;
                m.Message = "文件为空！";
                return m;
            }
            //检查文件是否有扩展名
            if (!Path.HasExtension(fileName))
            {
                m.Success = false;
                m.Message = "文件格式有误！";
                return m;
            }

            string fileExtension = Path.GetExtension(fileName).ToLower();

            //检查保存路径是否有误
            try
            {
                string p1 = root.EndsWith("/") ? root + DateTime.Now.ToString(TIME_FORMAT1) : root + "/" + DateTime.Now.ToString(TIME_FORMAT1) + "/";
                string filePath = context.Server.MapPath(p1);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string name = DateTime.Now.ToString(TIME_FORMAT2) + fileExtension;
                file.SaveAs(filePath + name);
                m.Success = true;
                m.Url = p1 + name;
            }
            catch (Exception ex)
            {
                m.Success = false;
                m.Message = ex.Message;
            }
            return m;
        }

        #endregion
    }
}